package com.zhs.gccs.view.taskMap;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.annimon.stream.Stream;
import com.zhs.gccs.R;
import com.zhs.gccs.adapter.TaskAreaAdapter;
import com.zhs.gccs.model.XzqArea;
import com.zhs.gccs.utils.SoftKeyboardUtils;
import com.zhs.gccs.utils.ToastUtils;
import com.zhs.gccs.view.BaseView;

import java.util.ArrayList;
import java.util.List;

public class XzqSelectView extends BaseView {
    private TextView tv_cancel;
    private TextView tv_confirm;

    private EditText et_search;
    private View v_search;
    private View ll_clean;

    private RecyclerView rv_province;
    private TaskAreaAdapter provinceAdapter;
    private List<XzqArea> provinces;
    private RecyclerView rv_city;
    private List<XzqArea> cities;
    private TaskAreaAdapter cityAdapter;
    private View ll_city_all;
    private CheckBox cb_city_all;

    private RecyclerView rv_district;
    private TaskAreaAdapter districtAdapter;
    private List<XzqArea> districts;
    private View ll_district_all;
    private CheckBox cb_district_all;

    public XzqSelectView(@NonNull Context context) {
        super(context);
    }

    public XzqSelectView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public XzqSelectView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void init(Context context, AttributeSet attrs, int defStyleAttr) {
        View view = LayoutInflater.from(context).inflate(R.layout.view_xzq,
                this, true);
        tv_cancel = view.findViewById(R.id.tv_cancel);
        tv_confirm = view.findViewById(R.id.tv_confirm);

        et_search = view.findViewById(R.id.et_search);
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(!TextUtils.isEmpty(charSequence.toString())){
                    ll_clean.setVisibility(VISIBLE);
                }else {
                    ll_clean.setVisibility(GONE);
                }
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        v_search = view.findViewById(R.id.v_search);
        ll_clean = view.findViewById(R.id.ll_clean);
        v_search.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                SoftKeyboardUtils.hideSoftInput(context,et_search);
                String name = et_search.getText().toString();
                if(TextUtils.isEmpty(name)){
                    return;
                }
                List<XzqArea> resultAreas = new ArrayList<>();
                List<XzqArea> areas = Stream.of(gtAreas)
                        .filter(i -> i.getXzqhmc().contains(name))
                        .toList();
                if(areas==null||areas.size()==0){
                    ToastUtils.toast("搜索的区域不存在");
                    return;
                }
                resultAreas.addAll(areas);
                Stream.of(areas).forEach(item->{
                    //向上
                    getAreaParent(resultAreas,item);
                    //向下
                    getAreaChildren(resultAreas,item);
                });
                gtFilterAreas = new ArrayList<>();
                gtFilterAreas.addAll(resultAreas);
                initDefault();
            }
            private void getAreaParent(List<XzqArea> areas, XzqArea item) {
                if(item.getParent()!=null){
                    XzqArea firstOrElse = Stream.of(areas).
                            filter(i -> i.getXzqhdm().equals(item.getParent().getXzqhdm())).
                            findFirstOrElse(null);
                    if(firstOrElse==null){
                        areas.add(item.getParent());
                    }
                    getAreaParent(areas,item.getParent());
                }
            }
            private void getAreaChildren(List<XzqArea> areas, XzqArea item) {
                if(item.getChildren()!=null){
                    Stream.of(item.getChildren())
                    .forEach(child->{
                        XzqArea firstOrElse = Stream.of(areas).
                                filter(i -> i.getXzqhdm().equals(child.getXzqhdm())).
                                findFirstOrElse(null);
                        if(firstOrElse==null){
                            areas.add(child);
                        }
                        getAreaChildren(areas,child);
                    });
                }
            }
        });
        ll_clean.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                SoftKeyboardUtils.hideSoftInput(context,et_search);
                et_search.setText("");
                ll_clean.setVisibility(GONE);
                gtFilterAreas = new ArrayList<>();
                gtFilterAreas.addAll(gtAreas);
                initDefault();
            }
        });

        rv_province = view.findViewById(R.id.rv_province);
        rv_city = view.findViewById(R.id.rv_city);
        rv_district = view.findViewById(R.id.rv_district);

        ll_city_all = view.findViewById(R.id.ll_city_all);
        cb_city_all = view.findViewById(R.id.cb_city_all);
        ll_district_all = view.findViewById(R.id.ll_district_all);
        cb_district_all = view.findViewById(R.id.cb_district_all);

        this.provinces = new ArrayList<>();
        rv_province.setLayoutManager(new LinearLayoutManager(context));
        provinceAdapter = new TaskAreaAdapter(context, this.provinces);
        rv_province.setAdapter(provinceAdapter);
        provinceAdapter.setOperationListener(new TaskAreaAdapter.OperationListener() {
            @Override
            public void onItemClick(int position) {
                provinceAdapter.setSelectedIndex(position);
                provinceAdapter.notifyDataSetChanged();
                XzqArea province = provinces.get(position);
                List<XzqArea> areas = Stream.of(gtFilterAreas).filter(i -> i.getXzqhpdm().equals(province.getXzqhdm())).toList();
                cities.clear();
                if (areas != null) cities.addAll(areas);
                cityAdapter.setSelectedIndex(-1);
                cityAdapter.notifyDataSetChanged();
                districts.clear();
                //初始化区
                if (cities != null && cities.size() > 0) {
                    List<XzqArea> areaDistricts = Stream.of(gtFilterAreas).filter(i -> i.getXzqhpdm().equals(cities.get(0).getXzqhdm())).toList();
                    districts.clear();
                    if (areaDistricts != null) districts.addAll(areaDistricts);
                }
                districtAdapter.notifyDataSetChanged();

                long countP = Stream.of(provinces).filter(i -> i.isChecked()).count();
                boolean pAll = countP == provinces.size() ? true : false;

                long countC = Stream.of(cities).filter(i -> i.isChecked()).count();
                boolean cAll = countC == cities.size() ? true : false;
                cb_city_all.setChecked(cAll);

                long countD = Stream.of(districts).filter(i -> i.isChecked()).count();
                boolean dAll = countD == districts.size() ? true : false;
                cb_district_all.setChecked(dAll);
            }

            @Override
            public void onItemCheckedChange(int position) {
                XzqArea province = provinces.get(position);
                province.setChecked(!province.isChecked());
                provinceAdapter.notifyItemChanged(position);
                List<XzqArea> areas = Stream.of(gtFilterAreas).
                        filter(i -> i.getXzqhpdm().equals(province.getXzqhdm())).toList();
                cities.clear();
                if (areas != null) cities.addAll(areas);
                //市联动
//                for(XzqArea c:cities){
//                    c.setChecked(province.isChecked());
//                }
                cityAdapter.notifyDataSetChanged();
                if (onItemChangeListener != null) onItemChangeListener.onItemChanged();

                long countP = Stream.of(provinces).filter(i -> i.isChecked()).count();
                boolean pAll = countP == provinces.size() ? true : false;

                long countC = Stream.of(cities).filter(i -> i.isChecked()).count();
                boolean cAll = countC == cities.size() ? true : false;
                cb_city_all.setChecked(cAll);

                long countD = Stream.of(districts).filter(i -> i.isChecked()).count();
                boolean dAll = countD == districts.size() ? true : false;
                cb_district_all.setChecked(dAll);


            }
        });

        this.cities = new ArrayList<>();
        rv_city.setLayoutManager(new LinearLayoutManager(context));
        cityAdapter = new TaskAreaAdapter(context, this.cities);
        rv_city.setAdapter(cityAdapter);
        cityAdapter.setOperationListener(new TaskAreaAdapter.OperationListener() {
            @Override
            public void onItemClick(int position) {
                cityAdapter.setSelectedIndex(position);
                cityAdapter.notifyDataSetChanged();
                XzqArea city = cities.get(position);
                List<XzqArea> areas = Stream.of(gtFilterAreas).filter(i -> i.getXzqhpdm().equals(city.getXzqhdm())).toList();
                districts.clear();
                if (areas != null) districts.addAll(areas);
                districtAdapter.notifyDataSetChanged();

                long countC = Stream.of(cities).filter(i -> i.isChecked()).count();
                boolean cAll = countC == cities.size() ? true : false;
                cb_city_all.setChecked(cAll);

                long countD = Stream.of(districts).filter(i -> i.isChecked()).count();
                boolean dAll = countD == districts.size() ? true : false;
                cb_district_all.setChecked(dAll);
            }

            @Override
            public void onItemCheckedChange(int position) {
                XzqArea city = cities.get(position);
                city.setChecked(!city.isChecked());
                cityAdapter.notifyItemChanged(position);
                List<XzqArea> areas = Stream.of(gtFilterAreas).filter(i -> i.getXzqhpdm().equals(city.getXzqhdm())).toList();
                districts.clear();
                if (areas != null) districts.addAll(areas);
                //不联动
//                for(XzqArea c:districts){
//                    c.setChecked(city.isChecked());
//                }
                districtAdapter.notifyDataSetChanged();
                if (onItemChangeListener != null) onItemChangeListener.onItemChanged();

                long countC = Stream.of(cities).filter(i -> i.isChecked()).count();
                boolean cAll = countC == cities.size() ? true : false;
                cb_city_all.setChecked(cAll);

                long countD = Stream.of(districts).filter(i -> i.isChecked()).count();
                boolean dAll = countD == districts.size() ? true : false;
                cb_district_all.setChecked(dAll);


                XzqArea province = Stream.of(provinces).filter(i -> i.getXzqhdm().equals(city.getXzqhpdm()))
                        .findFirstOrElse(null);
                if (countC > 0) {
                    province.setChecked(true);
                } else {
                    province.setChecked(false);
                }
                provinceAdapter.notifyDataSetChanged();
            }
        });
        ll_city_all.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                cb_city_all.setChecked(!cb_city_all.isChecked());
                Stream.of(cities).forEach(item -> item.setChecked(cb_city_all.isChecked()));
                cityAdapter.notifyDataSetChanged();
                if (onItemChangeListener != null) onItemChangeListener.onItemChanged();


                long countC = Stream.of(cities).filter(i -> i.isChecked()).count();
                XzqArea province = provinceAdapter.getSelectedIndexItem();
                if (countC > 0) {
                    province.setChecked(true);
                } else {
                    province.setChecked(false);
                }
                provinceAdapter.notifyDataSetChanged();
            }
        });


        this.districts = new ArrayList<>();
        rv_district.setLayoutManager(new LinearLayoutManager(context));
        districtAdapter = new TaskAreaAdapter(context, this.districts);
        rv_district.setAdapter(districtAdapter);
        districtAdapter.setOperationListener(new TaskAreaAdapter.OperationListener() {
            @Override
            public void onItemClick(int position) {
            }

            @Override
            public void onItemCheckedChange(int position) {
                XzqArea district = districts.get(position);
                district.setChecked(!district.isChecked());
                districtAdapter.notifyItemChanged(position);
                if (onItemChangeListener != null) onItemChangeListener.onItemChanged();

                long countD = Stream.of(districts).filter(i -> i.isChecked()).count();
                boolean dAll = countD == districts.size() ? true : false;
                cb_district_all.setChecked(dAll);

                XzqArea city = Stream.of(cities).filter(i -> i.getXzqhdm().equals(district.getXzqhpdm()))
                        .findFirstOrElse(null);
                XzqArea province = Stream.of(provinces).filter(i -> i.getXzqhdm().equals(city.getXzqhpdm()))
                        .findFirstOrElse(null);
                if (countD > 0) {
                    city.setChecked(true);
                    province.setChecked(true);
                } else {
                    city.setChecked(false);
                    province.setChecked(false);
                }
                provinceAdapter.notifyDataSetChanged();
                cityAdapter.notifyDataSetChanged();
            }
        });
        ll_district_all.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_district_all.setChecked(!cb_district_all.isChecked());
                Stream.of(districts).forEach(item -> item.setChecked(cb_district_all.isChecked()));
                districtAdapter.notifyDataSetChanged();
                if (onItemChangeListener != null) onItemChangeListener.onItemChanged();
                //级联上级
                long countD = Stream.of(districts).filter(i -> i.isChecked()).count();
                XzqArea city = cityAdapter.getSelectedIndexItem();
                XzqArea province = Stream.of(provinces).filter(i -> i.getXzqhdm().equals(city.getXzqhpdm()))
                        .findFirstOrElse(null);
                if (countD > 0) {
                    city.setChecked(true);
                    province.setChecked(true);
                } else {
                    city.setChecked(false);
                    province.setChecked(false);
                }
                provinceAdapter.notifyDataSetChanged();
                cityAdapter.notifyDataSetChanged();
            }
        });

        tv_cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                SoftKeyboardUtils.hideSoftInput(context,et_search);
                Stream.of(gtAreas).forEach(item -> item.setChecked(false));
                provinceAdapter.notifyDataSetChanged();
                cityAdapter.notifyDataSetChanged();
                districtAdapter.notifyDataSetChanged();
                cb_city_all.setChecked(false);
                cb_district_all.setChecked(false);
                if (onItemChangeListener != null) onItemChangeListener.onItemChanged();
            }
        });
        tv_confirm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                SoftKeyboardUtils.hideSoftInput(context,et_search);
                if (onItemChangeListener != null) onItemChangeListener.dismis();
            }
        });
    }

    List<XzqArea> gtAreas;
    private List<XzqArea> tree;
    private List<XzqArea> gtFilterAreas;

    public void initData(List<XzqArea> gtAreas) {
        if (gtAreas == null) return;
        this.gtAreas = gtAreas;
        gtFilterAreas = new ArrayList<>();
        gtFilterAreas.addAll(gtAreas);
        //组装树结构
        this.tree = buildTree("000000",gtFilterAreas);
        initDefault();
    }

//    public void setAreaSelect(XzqArea item) {
//        if (this.gtAreas == null) return ;
//        XzqArea firstOrElse = Stream.of(this.gtAreas)
//                .filter(i -> i.getXzqhdm().equals(item.getXzqhdm())).findFirstOrElse(null);
//        if(firstOrElse!=null){
//            firstOrElse.setChecked(true);
//        }
//    }

    private void initDefault() {
        List<XzqArea> areas = Stream.of(this.gtFilterAreas)
                .filter(i -> i.getXzqhpdm().equals("000000")).toList();
        this.provinces.clear();
        this.provinces.addAll(areas);
        this.provinceAdapter.notifyDataSetChanged();
        cb_city_all.setChecked(false);
        cb_district_all.setChecked(false);
        //初始化市
        if (this.provinces != null && this.provinces.size() > 0) {
            //初始化区
            XzqArea province = provinces.get(0);
            List<XzqArea> areaCities = Stream.of(gtFilterAreas).
                    filter(i -> i.getXzqhpdm().equals(province.getXzqhdm())).toList();
            provinceAdapter.setSelectedIndex(0);
            cities.clear();
            if (areaCities != null) cities.addAll(areaCities);
            cityAdapter.notifyDataSetChanged();
        }
        if (this.cities != null && this.cities.size() > 0) {
            XzqArea city = cities.get(0);
            List<XzqArea> areaDistricts = Stream.of(gtFilterAreas)
                    .filter(i -> i.getXzqhpdm().equals(city.getXzqhdm())).toList();
            cityAdapter.setSelectedIndex(0);
            districts.clear();
            if (areaDistricts != null) districts.addAll(areaDistricts);
            districtAdapter.notifyDataSetChanged();
        }
    }

    private List<XzqArea> buildTree(String pid, List<XzqArea> gtAreas) {
        List<XzqArea> areas = Stream.of(this.gtAreas)
                .filter(i -> i.getXzqhpdm().equals(pid)).toList();
        Stream.of(areas).forEach(item->{
            List<XzqArea> children = buildTree(item.getXzqhdm(),gtAreas);
            item.setChildren(children);
            if(children!=null&&children.size()>0){
                Stream.of(children).forEach(c->c.setParent(item));
                item.setHasChildren(true);
            }else {
                item.setHasChildren(false);
            }
        });
        return areas;
    }



    public List<XzqArea> getSelectedItems() {
        if (this.gtAreas == null) return null;
        List<XzqArea> areas = Stream.of(this.gtAreas)
                .filter(i -> i.isChecked()&&!i.isHasChildren())//只显示叶子节点
                .toList();
        return areas;
    }

    public List<String> getSelectedValue() {
        return Stream.of(this.gtAreas)
                .filter(i -> i.isChecked())
                .map(i -> i.getXzqhdm())
                .toList();
    }

    private OnItemChangeListener onItemChangeListener;

    public void setOnItemChangeListener(OnItemChangeListener onItemChangeListener) {
        this.onItemChangeListener = onItemChangeListener;
    }

    public void loseFocuse() {
//        SoftKeyboardUtils.hideSoftInput(context,et_search);
    }




    public interface OnItemChangeListener {
        void onItemChanged();

        void dismis();
    }
}
